﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.RoleMenuCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.RoleMenuCommandHandler
{
    /// <summary>
    /// 用户id的权限(菜单)
    /// </summary>
    public class GetRoleMenuCommandHandler : IRequestHandler<GetRoleMenuCommand, APIResult<List<MenuDTOs>>>
    {

        private readonly IBaseRepository<RoleMenuModel> roleMenuRepos;
        private readonly IBaseRepository<MenuModel> menuRepos;
        private readonly IBaseRepository<UserRole> userRoleRepos;

        public GetRoleMenuCommandHandler(
            IBaseRepository<RoleMenuModel> roleMenuRepos,
            IBaseRepository<MenuModel> menuRepos,
            IBaseRepository<UserRole> userRoleRepos
            )
        {
            this.roleMenuRepos = roleMenuRepos;
            this.menuRepos = menuRepos;
            this.userRoleRepos = userRoleRepos;
        }

        /// <summary>
        /// 通过用户id查询所对应的菜单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<MenuDTOs>>> Handle(GetRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDTOs>> result = new APIResult<List<MenuDTOs>>();
            //用户角色关系-查到含有对应UserId的
            var getRoleId = userRoleRepos.GetAll().Result.Where(x=>x.UserId == request.UserId).ToList();
            //RoleId[]3,1
            int[] roleId = getRoleId.Select(x => x.RoleId).ToList().ToArray();

            var getRoleMenu = roleMenuRepos.GetAll().Result.Where(x=> roleId.Contains(x.RoleId)).ToList();
            var list = from a in getRoleMenu
                       join b in menuRepos.GetAll().Result on a.MenuId equals b.MenuId
                       select new MenuDTOs
                       {
                           MenuId = a.MenuId,
                           RoleMenuId = a.RoleMenuId,
                           RoleId = a.RoleId,
                           MenuName = b.MenuName,
                           Url = b.Url,
                           ParentId = b.ParentId,
                       };
            int num = list.Count();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功 + $"共查询到{num}条";
            result.data = list.ToList();
            return await Task.FromResult(result);
        }
    }
}
